﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using SYcwpb.Helpers;
using SYcwpb.ViewModels;
using System.IO;
using System.Xml;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Markup;
using System.Data;
using System.Collections;
using Microsoft.Windows.Controls;
using System.Threading;
using System.ComponentModel;
using System.Windows.Threading;
using LogHelp;


namespace SYcwpb.Views
{
    /// <summary>
    /// MonthlyPlan.xaml 的交互逻辑
    /// </summary>
    public partial class MonthlyPlan : Window
    {
        public Log log = new Log();
        private static MonthlyPlan _instance = null;
        private MonthlyPlanModel _viewModel = null;
        private DriverTeamViewModel _driverTeamViewModel = null;
        //private GroupBackGroundColor _colorConvert = null;

        private bool isShowing = false;
        //导出排班Excel表
        public Thread ExportAssignExcelThread = null;


        private ShowTip tip;


        //保存路径
        private string filePath = "";

        private int year;
        private int month;
        private int totalday;
        private int startday;
        private int endday;

        private string planeStartDay;
        private string planeEndDay;

        private string queryplaneStartDay;
        private string queryPlaneEndDay;
        private string driverName="";
        private string driverNo = "";


        private Dictionary<string, string> updatedBeizhu = new Dictionary<string, string>();


        public MonthlyPlan()
        {
            InitializeComponent();
            _driverTeamViewModel = new DriverTeamViewModel();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        public static MonthlyPlan GetInsatance()
        {
            if (_instance == null || WindowHelper.IsDisposed(_instance))
                _instance = new MonthlyPlan();

            return _instance;
        }

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Maximized;
            _viewModel = new MonthlyPlanModel();
            this.DataContext = _viewModel;
            comboBox1.ItemsSource = _driverTeamViewModel.GetClassTurnPlaneRecord().DefaultView;
            comboBox1.DisplayMemberPath = "re_date";
            comboBox1.SelectedValuePath = "re_date";

           
        }
        public DataTemplate GetBeizhuHeadTemplate()
        {
            DataTemplate Header;
            StringBuilder tempString = new StringBuilder();
            StringReader srHeader;

            XmlReader Headerxml;

            string ns = "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"";
            tempString.Append("<DataTemplate " + ns + ">");
            tempString.Append(" <StackPanel Margin=\"-11,0,0,0\" HorizontalAlignment=\"Stretch\"");
            tempString.Append("                VerticalAlignment=\"Stretch\">");
            tempString.Append(" <Border>");
            tempString.Append(" <Label Content=\"\" Width=\"100\" ");

            tempString.Append("  HorizontalContentAlignment=\"Center\"/>");
            tempString.Append("  </Border>");
            tempString.Append(" <Border>");
            tempString.Append("  <GridSplitter BorderBrush=\"Black\"");
            tempString.Append("      BorderThickness=\"0.5\"");
            tempString.Append("    HorizontalAlignment=\"Stretch\"/>");
            tempString.Append(" </Border>");
            tempString.Append(" <Border>");
            tempString.Append("  <StackPanel Width=\"100\" Orientation=\"Horizontal\">");
            tempString.Append("  <Label Content=\"\" Width=\"100\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");
            tempString.Append("   </StackPanel>");
            tempString.Append(" </Border>");

            //////////////////////////////////////////////////////////////////////////////////
            tempString.Append(" <Border>");
            tempString.Append("  <GridSplitter BorderBrush=\"Black\"");
            tempString.Append("      BorderThickness=\"0.5\"");
            tempString.Append("    HorizontalAlignment=\"Stretch\"/>");
            tempString.Append(" </Border>");

            tempString.Append(" <Border>");
            tempString.Append("  <StackPanel Width=\"100\" Orientation=\"Horizontal\">");


            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("  <Label Content=\"备注\" Width=\"100\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");



            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("   </StackPanel>");
            tempString.Append(" </Border>");
            //////////////////////////////////////////////////////////////////////////////////
            tempString.Append("  </StackPanel>");
            tempString.Append("  </DataTemplate>");
            srHeader = new StringReader(tempString.ToString());
            //Create a DataTemplate from the XML
            Headerxml = XmlReader.Create(srHeader);
            Header = (DataTemplate)XamlReader.Load(Headerxml);
            return Header;
        }
        public DataTemplate GetHeadTemplate(string colName, string time)
        {
            DataTemplate Header;
            StringBuilder tempString = new StringBuilder();
            StringReader srHeader;

            XmlReader Headerxml;

            string ns = "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"";
            tempString.Append("<DataTemplate " + ns + ">");
            tempString.Append(" <StackPanel HorizontalAlignment=\"Stretch\" Margin=\"0,0,-11,0\"");
            tempString.Append("                VerticalAlignment=\"Stretch\">");
            tempString.Append(" <Border>");
            tempString.Append(" <Label Content=\"" + colName + "\" Width=\"500\" ");

            tempString.Append("  HorizontalContentAlignment=\"Center\"/>");
            tempString.Append("  </Border>");
            tempString.Append(" <Border>");
            tempString.Append("  <GridSplitter BorderBrush=\"Black\"");
            tempString.Append("      BorderThickness=\"0.5\"");
            tempString.Append("    HorizontalAlignment=\"Stretch\"/>");
            tempString.Append(" </Border>");
            tempString.Append(" <Border>");
            // tempString.Append("  <StackPanel Width=\"160\" Orientation=\"Horizontal\">");
            tempString.Append("  <Label Content=\"" + time + "\" Width=\"500\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");
            // tempString.Append("   </StackPanel>");
            tempString.Append(" </Border>");

            //////////////////////////////////////////////////////////////////////////////////
            tempString.Append(" <Border>");
            tempString.Append("  <GridSplitter BorderBrush=\"Black\"");
            tempString.Append("      BorderThickness=\"0.5\"");
            tempString.Append("    HorizontalAlignment=\"Stretch\"/>");
            tempString.Append(" </Border>");

            tempString.Append(" <Border>");
            tempString.Append("  <StackPanel Width=\"500\" Orientation=\"Horizontal\">");
            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("  <Label Content=\"班次\" Width=\"65\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");
            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("  <Label Content=\"出勤信息\" Width=\"100\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");
            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("  <Label Content=\"公里数\" Width=\"65\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");
            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("  <Label Content=\"小时数\" Width=\"65\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");
            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("  <Label Content=\"调班\" Width=\"200\" ");
            tempString.Append("  HorizontalContentAlignment=\"Center\"");
            tempString.Append("  VerticalContentAlignment=\"Center\"/>");




            tempString.Append(" <GridSplitter BorderBrush=\"Black\"  BorderThickness=\"0.5\"/>");
            tempString.Append("   </StackPanel>");
            tempString.Append(" </Border>");
            //////////////////////////////////////////////////////////////////////////////////
            tempString.Append("  </StackPanel>");
            tempString.Append("  </DataTemplate>");
            srHeader = new StringReader(tempString.ToString());
            //Create a DataTemplate from the XML
            Headerxml = XmlReader.Create(srHeader);
            Header = (DataTemplate)XamlReader.Load(Headerxml);
            return Header;
        }

        public DataTemplate GetCellTemplate(string colName)
        {
            DataTemplate cell;
            StringBuilder cellString = new StringBuilder();
            StringReader srcell;
            XmlReader cellxml;
            string ns = "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"";
            cellString.Append("<DataTemplate " + ns + ">");
            cellString.Append("<StackPanel Width=\"Auto\" Height=\"Auto\" Orientation=\"Horizontal\">");
            cellString.Append("<Border>");
            cellString.Append("  <TextBlock Margin=\"1,0,1,0\"  Width=\"64\"");
            cellString.Append("     Text=\"{Binding " + colName + "}\"");
            cellString.Append("    HorizontalAlignment=\"Center\"");
            cellString.Append("   VerticalAlignment=\"Center\"/>");
            cellString.Append(" </Border>");
            cellString.Append(" <Border>");
            cellString.Append(" <GridSplitter Background=\"Black\" ");
            cellString.Append("  BorderThickness=\"0.5\"");
            cellString.Append("  BorderBrush=\"Black\"");
            cellString.Append(" Margin=\"0,-1,0,-1\"/>");
            cellString.Append(" </Border>");
            cellString.Append("<Border>");
            cellString.Append("  <TextBlock Margin=\"1,0,1,0\"  Width=\"100\"");
            cellString.Append("     Text=\"{Binding " + colName + "Q}\"");
            cellString.Append("    HorizontalAlignment=\"Center\"");
            cellString.Append("   VerticalAlignment=\"Center\"/>");
            cellString.Append(" </Border>");
            cellString.Append(" <Border>");
            
            cellString.Append(" <GridSplitter Background=\"Black\" ");
            cellString.Append("  BorderThickness=\"0.5\"");
            cellString.Append("  BorderBrush=\"Black\"");
            cellString.Append(" Margin=\"0,-1,0,-1\"/>");
            cellString.Append(" </Border>");
            cellString.Append("<Border>");
            cellString.Append("  <TextBlock Margin=\"1,0,1,0\"  Width=\"65\"");
            cellString.Append("     Text=\"{Binding " + colName + "M}\"");
            cellString.Append("    HorizontalAlignment=\"Center\"");
            cellString.Append("   VerticalAlignment=\"Center\"/>");
            cellString.Append(" </Border>");

            cellString.Append(" <Border>");
            cellString.Append(" <GridSplitter Background=\"Black\" ");
            cellString.Append("  BorderThickness=\"0.5\"");
            cellString.Append("  BorderBrush=\"Black\"");
            cellString.Append(" Margin=\"0,-1,0,-1\"/>");
            cellString.Append(" </Border>");
            cellString.Append("<Border>");
            cellString.Append("  <TextBlock Margin=\"1,0,1,0\"  Width=\"65\"");
            cellString.Append("     Text=\"{Binding " + colName + "H}\"");
            cellString.Append("    HorizontalAlignment=\"Center\"");
            cellString.Append("   VerticalAlignment=\"Center\"/>");
            cellString.Append(" </Border>");
            cellString.Append(" <Border>");
            cellString.Append(" <GridSplitter Background=\"Black\" ");
            cellString.Append("  BorderThickness=\"0.5\"");
            cellString.Append("  BorderBrush=\"Black\"");
            cellString.Append(" Margin=\"0,-1,0,-1\"/>");
            cellString.Append(" </Border>");
            cellString.Append("<Border>");
            cellString.Append("  <TextBlock Margin=\"1,0,1,0\"  Width=\"200\"");
            cellString.Append("     Text=\"{Binding " + colName + "D}\"");
            cellString.Append("    HorizontalAlignment=\"Center\"");
            cellString.Append("   VerticalAlignment=\"Center\"/>");
            cellString.Append(" </Border>");

            //cellString.Append(" <Border>");
            //cellString.Append(" <GridSplitter Background=\"Black\" ");
            //cellString.Append("  BorderThickness=\"0.5\"");
            //cellString.Append("  BorderBrush=\"Black\"");
            //cellString.Append(" Margin=\"0,-1,0,-1\"/>");
            //cellString.Append(" </Border>");
            //cellString.Append("<Border>");
            //cellString.Append("  <TextBox BorderThickness=\"0\" IsReadOnly=\"True\"  Command=\"{Binding EditBeiZhuCommand }\" Background=\"Transparent\" Margin=\"1,0,1,0\"  Width=\"100\"");
            //cellString.Append("     Text=\"{Binding " + colName + "R}\"");
            //cellString.Append("    HorizontalAlignment=\"Center\"");
            //cellString.Append("   VerticalAlignment=\"Center\"/>");
            //cellString.Append(" </Border>");

            cellString.Append(" </StackPanel>");
            cellString.Append(" </DataTemplate>");
            srcell = new StringReader(cellString.ToString());
            cellxml = XmlReader.Create(srcell);
            cell = (DataTemplate)XamlReader.Load(cellxml);
            return cell;
        }

        public void DataBind(DataTable dt, Hashtable has, DataGrid dg)
        {

            //dg.ItemsSource = null;
            dg.Columns.Clear();
            //dg.DataContext = null;

            foreach (DataColumn col in dt.Columns)
            {

                if (col.ColumnName == "dcdr_team")
                {

                    dg.Columns.Add(new DataGridTextColumn() { Header = "组名", Binding = new Binding("dcdr_team") ,IsReadOnly=true});

                }
                else if (col.ColumnName == "dcdr_userid")
                {
                    var column = new DataGridTextColumn() { Header = "userid", Binding = new Binding("dcdr_userid"), IsReadOnly = true ,Visibility=Visibility.Hidden};
                    dg.Columns.Add(column);
                }
                else if (col.ColumnName == "dcom_NO")
                {
                    dg.Columns.Add(new DataGridTextColumn() { Header = "司机组", Binding = new Binding("dcom_NO"), IsReadOnly = true });
                }
                else if (col.ColumnName == "dcdr_userName")
                {
                    dg.Columns.Add(new DataGridTextColumn() { Header = "司机姓名", Binding = new Binding("dcdr_userName"), IsReadOnly = true });
                }
                else if (col.ColumnName == "MTotal")
                {
                    dg.Columns.Add(new DataGridTextColumn() { Header = "总公里数", Binding = new Binding("MTotal"), IsReadOnly = true });
                }
                else if (col.ColumnName == "MHours")
                {
                    dg.Columns.Add(new DataGridTextColumn() { Header = "总工时", Binding = new Binding("MHours"), IsReadOnly = true });
                }
                else
                {
                    if (!col.ColumnName.Contains("M") && !col.ColumnName.Contains("H") 
                        && !col.ColumnName.Contains("Q") && !col.ColumnName.Contains("D")
                        &&!col.ColumnName.Contains("R") )
                    {
                        DataTemplate head = GetHeadTemplate(col.ColumnName, has[col.ColumnName].ToString());
                        DataTemplate cell = GetCellTemplate(col.ColumnName);
                        var c = new DataGridTemplateColumn();
                        c.CellTemplate = cell;
                        c.HeaderTemplate = head;
                        c.IsReadOnly = true;
                        dg.Columns.Add(c);
                    }
                    else if (col.ColumnName.Contains("R"))
                    {

                        var c = new DataGridTextColumn() { Binding = new Binding(col.ColumnName),IsReadOnly=false };
                        c.HeaderTemplate = GetBeizhuHeadTemplate();
                        dg.Columns.Add(c);
                    }
                }
            }

            dg.AutoGenerateColumns = false;

            dg.FrozenColumnCount = 5;

            dg.ItemsSource = dt.DefaultView;
        }

        //一行行修改背景颜色（存在问题）
        public delegate void ToChangeColor();
        public void ChangeColor()
        {
            try
            {

                for (int i = 0; i < dataGrid.Items.Count; i++)
                {
                    DataRowView drv = dataGrid.Items[i] as DataRowView;
                    int group = Convert.ToInt32(drv["dcdr_team"]);
                    if (group == 1)
                    {
                        var row = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[i]) as DataGridRow;
                        if (row != null)
                        {
                            row.Background = new SolidColorBrush(Colors.Red);
                            row.Foreground = new SolidColorBrush(Colors.Black);
                        }
                    }
                    else if (group == 2)
                    {
                        var row = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[i]) as DataGridRow;
                        if (row != null)
                        {
                            row.Background = new SolidColorBrush(Colors.Black);
                            row.Foreground = new SolidColorBrush(Colors.Red);
                        }
                    }
                    else if (group == 3)
                    {
                        var row = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[i]) as DataGridRow;
                        if (row != null)
                            row.Background = new SolidColorBrush(Colors.Purple);
                    }
                    else
                    {
                        var row = dataGrid.ItemContainerGenerator.ContainerFromItem(dataGrid.Items[i]) as DataGridRow;
                        if (row != null)
                            row.Background = new SolidColorBrush(Colors.Pink);
                    }
                }
            }
            catch (Exception ex)
            {
                log.writeError(ex.ToString());
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //_colorConvert = new GroupBackGroundColor();
                updatedBeizhu.Clear();
                if (string.IsNullOrEmpty(comboBox1.Text))
                {
                    MessageBox.Show("请选择计划班表");
                    return;
                }
                if (dpStartDate.SelectedDate==null || dpEndDate.SelectedDate==null)
                {
                    MessageBox.Show("请输入起止日期");
                    return;
                }
                if(dpStartDate.SelectedDate>dpEndDate.SelectedDate)
                {
                    MessageBox.Show("开始日期不能大于结束日期");
                    return;
                }
                //else
                //{
                //    string[] date = comboBox1.Text.Split('-');
                //    year = Convert.ToInt32(date[0].ToString());
                //    month = Convert.ToInt32(date[1].ToString());
                //    totalday = DateTime.DaysInMonth(year, month);
                //    startday = Convert.ToInt32(startDay.Text.ToString());
                //    endday = Convert.ToInt32(endDay.Text.ToString());

                   
                //}
                queryplaneStartDay = Convert.ToDateTime(dpStartDate.SelectedDate).ToString("yyyy-MM-dd");
                queryPlaneEndDay = Convert.ToDateTime(dpEndDate.SelectedDate).ToString("yyyy-MM-dd");
                driverName = txtDriverName.Text;
                driverNo = txtDriverNo.Text;
                button1.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ToShowTable(ShowTable));
                //显示提示
                tip = new ShowTip();
                tip.ShowDialog();
                updatedBeizhu.Clear();
            }

            catch (Exception ex)
            {
                log.writeError(ex.ToString());
            }

        }

        //显示查询数据
        public delegate void ToShowTable();
        public void ShowTable()
        {
            try
            {
                isShowing = true;
                //获取数据表
                DataTable dt = new DataTable();
                //dt = _driverTeamViewModel.GetDriverCombineCrossingRoadPlane(year, month, startday, endday);
                dt = _driverTeamViewModel.GetDriverCombineCrossingRoadPlane(queryplaneStartDay,queryPlaneEndDay);

                //进行筛选
                if(string.IsNullOrEmpty(driverNo)==false || string.IsNullOrEmpty(driverName)==false)
                {
                    //从新给dt赋值
                    if (string.IsNullOrEmpty(driverNo))
                    {
                        driverNo = "-1";
                    }
                    else
                    {
                        driverNo = _driverTeamViewModel.GetUserNameById(driverNo);
                        if (string.IsNullOrEmpty(driverNo))
                        {
                            driverNo = "-1";
                        }
                        
                    }
                    DataRow[] drs = dt.Select("dcdr_userid="+driverNo+" or dcdr_userName='"+driverName+"' ");
                    if (drs.Length > 0)
                    {
                        dt = drs.CopyToDataTable();
                    }
                    else
                    {
                        dt.Clear();
                    }
                }
                
                //获取时刻表的名称
                Hashtable hasTbleNameWithDate = new Hashtable();
                //hasTbleNameWithDate = _driverTeamViewModel.GetTableNameWithDate(year, month, startday, endday);
                hasTbleNameWithDate = _driverTeamViewModel.GetTableNameWithDate(queryplaneStartDay,queryPlaneEndDay);
                //绑定数据
                DataBind(dt, hasTbleNameWithDate, dataGrid);
                isShowing = false;
                tip.Visibility = Visibility.Collapsed;
                tip.Close();
            }
            catch (Exception ex)
            {
                isShowing = false;
                tip.Visibility = Visibility.Collapsed;
                tip.Close();
                log.writeError(ex.ToString());
                MessageBox.Show("系统出错！");
            }
        }



        //保存导出数据
        private void btn_exportExcel_Click(object sender, RoutedEventArgs e)
        {


            if (string.IsNullOrEmpty(comboBox1.Text))
            {
                _viewModel.IsExporting = false;
                _viewModel.ExportInfoVisibility = Visibility.Collapsed;
                MessageBox.Show("请选择计划班表");
                return;
            }
            else
            {
                System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
                fbd.ShowNewFolderButton = true;
                fbd.Description = "请选择排班表的保存路径";

                if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
                {
                    _viewModel.IsExporting = false;
                    _viewModel.ExportInfoVisibility = Visibility.Collapsed;
                    return;
                }
                filePath = fbd.SelectedPath;
                if (!filePath.EndsWith("\\"))
                    filePath += "\\";
            }
            queryplaneStartDay =Convert.ToDateTime(dpStartDate.SelectedDate).ToString("yyyy-MM-dd");
            queryPlaneEndDay =Convert.ToDateTime(dpEndDate.SelectedDate).ToString("yyyy-MM-dd");
            driverName = txtDriverName.Text;
            driverNo = txtDriverNo.Text;
            Button b = sender as Button;
            if (b.Name == "normal")
            {
                btn_exportExcel.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ToExportAssignExcel(ExportAssignExcel));
            }
            else
            {
                btn_exportExcel.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new ToExportAssignExcel(ExportAssignExcelSimplify));
            }
            
            tip = new ShowTip();
            tip.ShowDialog();


            //_viewModel.ExportInfoVisibility = Visibility.Visible;

        }


        //导出
        public delegate void ToExportAssignExcel();
        public void ExportAssignExcel()
        {

               try
              {
                 _viewModel.IsExporting = true;
                  string fileName = string.Format("排班表_{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));
                  //string[] date = comboBox1.Text.Split('-');
                  //int year = Convert.ToInt32(date[0].ToString());
                  //int month = Convert.ToInt32(date[1].ToString());
                  //int totalday = DateTime.DaysInMonth(year, month);
                  //int startday = Convert.ToInt32(startDay.Text.ToString());
                  //int endday = Convert.ToInt32(endDay.Text.ToString());

                  //获取数据表
                  //DataTable sourceDataTable = _driverTeamViewModel.GetDriverCombineCrossingRoadPlane(year, month);
                  DataTable sourceDataTable = _driverTeamViewModel.GetDriverCombineCrossingRoadPlane(queryplaneStartDay,queryPlaneEndDay);

                  if (string.IsNullOrEmpty(driverNo) == false || string.IsNullOrEmpty(driverName) == false)
                  {
                      //从新给dt赋值
                      if (string.IsNullOrEmpty(driverNo))
                      {
                          driverNo = "-1";
                      }
                      else
                      {
                          driverNo = _driverTeamViewModel.GetUserNameById(driverNo);
                          if (string.IsNullOrEmpty(driverNo))
                          {
                              driverNo = "-1";
                          }

                      }
                      DataRow[] drs = sourceDataTable.Select("dcdr_userid=" + driverNo + " or dcdr_userName='" + driverName + "' ");
                      if (drs.Length > 0)
                      {
                          sourceDataTable = drs.CopyToDataTable();
                      }
                      else
                      {
                          sourceDataTable.Clear();
                         // return;
                      }
                  }
                  if (sourceDataTable.Rows.Count == 0)
                  {
                      _viewModel.IsExporting = false;
                      tip.Visibility = Visibility.Collapsed;
                      tip.Close();
                      MessageBox.Show("查询不到数据");
                     
                      return;
                  }

                  //获取时刻表的名称
                  //Hashtable schedule = _driverTeamViewModel.GetTableNameWithDate(year, month);

                  Hashtable schedule = _driverTeamViewModel.GetTableNameWithDate(queryplaneStartDay, queryPlaneEndDay);

                  //获取一个月有多少天
                  //int daysInMonth = DateTime.DaysInMonth(year, month);
                  
                  TimeSpan ts = Convert.ToDateTime(queryPlaneEndDay)-Convert.ToDateTime(queryplaneStartDay);
                  int daysCount = ts.Days+1;
                  //根据日期数量来构建DataTable的列
                  DataTable callPB = GetCallTable(daysCount);

                  InitCallTable(ref callPB, sourceDataTable, daysCount);

                  OutExcel excel = new OutExcel();
                  excel.ws.Cells[1, 1] = fileName.Split(' ')[0];
                  //横向合并表头
                  excel.UniteCells(excel.ws, 1, 1, 1, 6 + daysCount * 3);

                  excel.ws.Cells[2, 1] = "组别";// A
                  excel.UniteCells(excel.ws, 2, 1, 4, 1);//纵向合并组别

                  excel.ws.Cells[2, 2] = "序号";   // B
                  excel.UniteCells(excel.ws, 2, 2, 4, 2);//纵向合并序号

                  excel.ws.Cells[2, 3] = "司机组";  // C
                  excel.UniteCells(excel.ws, 2, 3, 4, 3);//纵向合并司机组

                  excel.ws.Cells[2, 4] = "司机";  // D.
                  excel.UniteCells(excel.ws, 2, 4, 4, 4);//纵向合并司机

                  excel.ws.Cells[2, 5] = "总公里数";  // D.
                  excel.UniteCells(excel.ws, 2, 5, 4, 5);//纵向合并总公里数

                  excel.ws.Cells[2, 6] = "总小时数";  // D.
                  excel.UniteCells(excel.ws, 2, 6, 4, 6);//纵向合并总小时数

                  //纵向合并组别，有一、二、三、四组
                  DataRow[] drone = sourceDataTable.Select("dcdr_team='1'");
                  DataTable dtOne;
                  if (drone.Length > 0)
                  {
                      dtOne = sourceDataTable.Select("dcdr_team='1'").CopyToDataTable();
                  }
                  else
                  {
                      dtOne = sourceDataTable.Clone();
                      dtOne.Clear();
 
                  }

                  DataRow[] drTwo = sourceDataTable.Select("dcdr_team='2'");
                  DataTable dtTwo;
                  if (drTwo.Length > 0)
                  {
                      dtTwo = sourceDataTable.Select("dcdr_team='2'").CopyToDataTable();
                  }
                  else
                  {
                      dtTwo = sourceDataTable.Clone();
                      dtTwo.Clear();

                  }

                  DataRow[] drThree = sourceDataTable.Select("dcdr_team='3'");
                  DataTable dtThree;
                  if (drThree.Length > 0)
                  {
                      dtThree = sourceDataTable.Select("dcdr_team='3'").CopyToDataTable();
                  }
                  else
                  {
                      dtThree = sourceDataTable.Clone();
                      dtThree.Clear();

                  }

                  DataRow[] drFour = sourceDataTable.Select("dcdr_team='4'");
                  DataTable dtFour;
                  if (drFour.Length > 0)
                  {
                      dtFour = sourceDataTable.Select("dcdr_team='4'").CopyToDataTable();
                  }
                  else
                  {
                      dtFour = sourceDataTable.Clone();
                      dtFour.Clear();

                  }
                 // DataTable dtOne = sourceDataTable.Select("dcdr_team='1'").CopyToDataTable();
                 // DataTable dtTwo = sourceDataTable.Select("dcdr_team='2'").CopyToDataTable();
                // DataTable dtThree = sourceDataTable.Select("dcdr_team='3'").CopyToDataTable();
                 // DataTable dtFour = sourceDataTable.Select("dcdr_team='4'").CopyToDataTable();
                  //第一组
                  //excel.ws.Cells[4, 1] = dtOne.Rows[0][0].ToString();
                  excel.ws.Cells[5, 1] = "电客车一组";
                  //excel.ws.Cells[3 + dtOne.Rows.Count, 1] = excel.ws.Cells[4, 1];
                  excel.UniteCells(excel.ws, 5, 1, 4 + dtOne.Rows.Count, 1);
                  
                  //第二组
                  //excel.ws.Cells[4 + dtOne.Rows.Count, 1] = dtTwo.Rows[0][0].ToString();
                  excel.ws.Cells[5 + dtOne.Rows.Count, 1] = "电客车二组";

                  excel.UniteCells(excel.ws, 5 + dtOne.Rows.Count, 1, 4 + dtOne.Rows.Count + dtTwo.Rows.Count, 1);
                  //第三组
                  //excel.ws.Cells[4 + dtOne.Rows.Count + dtTwo.Rows.Count, 1] = dtThree.Rows[0][0].ToString();
                  excel.ws.Cells[5 + dtOne.Rows.Count + dtTwo.Rows.Count, 1] = "电客车三组";
                  excel.UniteCells(excel.ws, 5 + dtOne.Rows.Count + dtTwo.Rows.Count, 1, 4 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1);
                  //第四组
                  //excel.ws.Cells[4 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1] = dtFour.Rows[0][0].ToString();
                  excel.ws.Cells[5 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1] = "电客司车四组";
                  excel.UniteCells(excel.ws, 5 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1, 4 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count + dtFour.Rows.Count, 1);


                  int index = 0;
                  int count = (sourceDataTable.Columns.Count - 5) / 5;
                  foreach (DataColumn dcl in sourceDataTable.Columns)
                  {
                      if (dcl.ColumnName != "dcdr_team" && dcl.ColumnName != "dcom_NO" && dcl.ColumnName != "dcdr_userName" && dcl.ColumnName != "MTotal" && dcl.ColumnName != "MHours" && dcl.ColumnName != "dcdr_userid"
                        && !dcl.ColumnName.Contains("M") && !dcl.ColumnName.Contains("H") && !dcl.ColumnName.Contains("D") && !dcl.ColumnName.Contains("Q") && !dcl.ColumnName.Contains("R") && count > 0)
                      {

                          //合并表头
                          excel.ws.Cells[2, 7 + index] = dcl.ColumnName;
                          excel.UniteCells(excel.ws, 2, 7 + index, 2, 7 + index + 5);
                          excel.ws.Cells[3, 7 + index] = schedule[dcl.ColumnName];
                          excel.UniteCells(excel.ws, 3, 7 + index, 3, 7 + index + 5);

                          excel.ws.Cells[4, 7 + index] = "班次";
                          excel.ws.Cells[4, 7 + index + 1] = "出勤地点";
                          excel.ws.Cells[4, 7 + index + 2] = "公里数";
                          excel.ws.Cells[4, 7 + index + 3] = "小时数";
                          excel.ws.Cells[4, 7 + index + 4] = "调班";
                          excel.ws.Cells[4, 7 + index + 5] = "备注";
                          
                          ((Excel.Range)excel.ws.Columns[7 + index+1, System.Type.Missing]).ColumnWidth = 20;
                          ((Excel.Range)excel.ws.Columns[7 + index + 5, System.Type.Missing]).ColumnWidth = 16;
                          index = index + 6;
                          count--;
                      }
                  }

                  //((Excel.Range)excel.ws.Columns[3, System.Type.Missing]).ColumnWidth = 16;
                  //((Excel.Range)excel.ws.Columns[4, System.Type.Missing]).ColumnWidth = 16;

                  ((Excel.Range)excel.ws.Cells[1, 1]).Font.Size = 18;
                  ((Excel.Range)excel.ws.Cells[1, 1]).Font.Color = Excel.Constants.xlColor1;


                  //  设置背景色及合并
                  string cell = sourceDataTable.Rows[0]["dcom_NO"].ToString();
                  //合并
                  int row = -1;
                  int sum = 0;
                  for (int i = 0; i < sourceDataTable.Rows.Count; i++)
                  {
                      string tem = sourceDataTable.Rows[i]["dcom_NO"].ToString();
                      if (tem == cell)
                      {
                          row++;
                      }
                      if (tem != cell)
                      {

                          if (row > 0)
                          {
                              excel.UniteCells(excel.ws, 5 + sum, 2, 5 + sum + row, 2);

                          }
                          sum += row;
                          sum++;
                          row = 0;
                          cell = tem;
                      }
                      if (i == sourceDataTable.Rows.Count - 1 && row > 0)
                      {
                          excel.UniteCells(excel.ws, 5 + sum, 2, 5 + sum + row, 2);
                      }

                    
                      ((Excel.Range)excel.ws.Rows[4 + i, System.Type.Missing]).RowHeight = 18;
                      //设置背景色
                      if (i% 2 == 0)
                      {
                          ((Excel.Range)excel.ws.Rows[5 + i, System.Type.Missing]).Interior.ColorIndex = 19;
                      }
                      else
                      {
                          ((Excel.Range)excel.ws.Rows[5 + i, System.Type.Missing]).Interior.ColorIndex = 39;
                      }

                  }

                  ((Excel.Range)excel.ws.Columns[2, System.Type.Missing]).Interior.ColorIndex = 0;
                  ((Excel.Range)excel.ws.Rows[2, System.Type.Missing]).Interior.ColorIndex = 19;
                  ((Excel.Range)excel.ws.Rows[3, System.Type.Missing]).Interior.ColorIndex = 19;
                  ((Excel.Range)excel.ws.Rows[4, System.Type.Missing]).Interior.ColorIndex = 39;

                  excel.InsertTable(callPB, excel.ws, 5, 1);

                  excel.SaveAs(string.Format("{0}{1}", filePath, fileName));

                  excel.Close();
                  excel.KillExcelProcess();

                  MessageBoxHelper.ShowTips(string.Format("导出 {0}  成功!", fileName));
              }
              catch (System.Exception ex)
              {
                  //MessageBoxHelper.ShowError(string.Format("导出排班表失败: {0}", ex.Message.ToString()));
                  MessageBoxHelper.ShowError(ex);
              }

              _viewModel.IsExporting = false;
              tip.Visibility = Visibility.Collapsed;
              tip.Close();
              //_viewModel.ExportInfoVisibility = Visibility.Collapsed;


        }
        public void ExportAssignExcelSimplify()
        {
            try
            {
                _viewModel.IsExporting = true;
                string fileName = string.Format("排班表_{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd HH_mm_ss"));

                DataTable sourceDataTable = _driverTeamViewModel.GetDriverCombineCrossingRoadPlane(queryplaneStartDay, queryPlaneEndDay);

                if (string.IsNullOrEmpty(driverNo) == false || string.IsNullOrEmpty(driverName) == false)
                {
                    //从新给dt赋值
                    if (string.IsNullOrEmpty(driverNo))
                    {
                        driverNo = "-1";
                    }
                    else
                    {
                        driverNo = _driverTeamViewModel.GetUserNameById(driverNo);
                        if (string.IsNullOrEmpty(driverNo))
                        {
                            driverNo = "-1";
                        }

                    }
                    DataRow[] drs = sourceDataTable.Select("dcdr_userid=" + driverNo + " or dcdr_userName='" + driverName + "' ");
                    if (drs.Length > 0)
                    {
                        sourceDataTable = drs.CopyToDataTable();
                    }
                    else
                    {
                        sourceDataTable.Clear();
                        // return;
                    }
                }
                if (sourceDataTable.Rows.Count == 0)
                {
                    _viewModel.IsExporting = false;
                    tip.Visibility = Visibility.Collapsed;
                    tip.Close();
                    MessageBox.Show("查询不到数据");

                    return;
                }

                Hashtable schedule = _driverTeamViewModel.GetTableNameWithDate(queryplaneStartDay, queryPlaneEndDay);


                TimeSpan ts = Convert.ToDateTime(queryPlaneEndDay) - Convert.ToDateTime(queryplaneStartDay);
                int daysCount = ts.Days + 1;
                //根据日期数量来构建DataTable的列
                DataTable callPB = GetCallTableSimplify(daysCount);

                InitCallTableSimplify(ref callPB, sourceDataTable, daysCount);

                OutExcel excel = new OutExcel();
                //excel.ws.Cells[1, 1] = fileName.Split(' ')[0];
                //横向合并表头
                //excel.UniteCells(excel.ws, 1, 1, 1, 6 + daysCount * 3);

                excel.ws.Cells[1, 1] = "组别";// A
                excel.UniteCells(excel.ws, 1, 1, 3, 1);//纵向合并组别

                excel.ws.Cells[1, 2] = "司机";  // D.
                excel.UniteCells(excel.ws, 1, 2, 3, 2);//纵向合并司机


                //纵向合并组别，有一、二、三、四组
                DataRow[] drone = sourceDataTable.Select("dcdr_team='1'");
                DataTable dtOne;
                if (drone.Length > 0)
                {
                    dtOne = sourceDataTable.Select("dcdr_team='1'").CopyToDataTable();
                }
                else
                {
                    dtOne = sourceDataTable.Clone();
                    dtOne.Clear();

                }

                DataRow[] drTwo = sourceDataTable.Select("dcdr_team='2'");
                DataTable dtTwo;
                if (drTwo.Length > 0)
                {
                    dtTwo = sourceDataTable.Select("dcdr_team='2'").CopyToDataTable();
                }
                else
                {
                    dtTwo = sourceDataTable.Clone();
                    dtTwo.Clear();
                }
                DataRow[] drThree = sourceDataTable.Select("dcdr_team='3'");
                DataTable dtThree;
                if (drThree.Length > 0)
                {
                    dtThree = sourceDataTable.Select("dcdr_team='3'").CopyToDataTable();
                }
                else
                {
                    dtThree = sourceDataTable.Clone();
                    dtThree.Clear();
                }
                DataRow[] drFour = sourceDataTable.Select("dcdr_team='4'");
                DataTable dtFour;
                if (drFour.Length > 0)
                {
                    dtFour = sourceDataTable.Select("dcdr_team='4'").CopyToDataTable();
                }
                else
                {
                    dtFour = sourceDataTable.Clone();
                    dtFour.Clear();
                }
                //第一组
                //excel.ws.Cells[4, 1] = dtOne.Rows[0][0].ToString();
                excel.ws.Cells[4, 1] = "电客车一组";
                //excel.ws.Cells[3 + dtOne.Rows.Count, 1] = excel.ws.Cells[4, 1];
                excel.UniteCells(excel.ws, 4, 1, 3 + dtOne.Rows.Count, 1);

                //第二组
                //excel.ws.Cells[4 + dtOne.Rows.Count, 1] = dtTwo.Rows[0][0].ToString();
                excel.ws.Cells[4 + dtOne.Rows.Count, 1] = "电客车二组";

                excel.UniteCells(excel.ws, 4 + dtOne.Rows.Count, 1, 3 + dtOne.Rows.Count + dtTwo.Rows.Count, 1);
                //第三组
                //excel.ws.Cells[4 + dtOne.Rows.Count + dtTwo.Rows.Count, 1] = dtThree.Rows[0][0].ToString();
                excel.ws.Cells[4 + dtOne.Rows.Count + dtTwo.Rows.Count, 1] = "电客车三组";
                excel.UniteCells(excel.ws, 4 + dtOne.Rows.Count + dtTwo.Rows.Count, 1, 3 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1);
                //第四组
                //excel.ws.Cells[4 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1] = dtFour.Rows[0][0].ToString();
                excel.ws.Cells[4 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1] = "电客司车四组";
                excel.UniteCells(excel.ws, 4 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count, 1, 3 + dtOne.Rows.Count + dtTwo.Rows.Count + dtThree.Rows.Count + dtFour.Rows.Count, 1);

                ((Excel.Range)excel.ws.Columns[1, System.Type.Missing]).ColumnWidth = 3;

                int index = 0;

                int count = (sourceDataTable.Columns.Count - 5) / 5;
                foreach (DataColumn dcl in sourceDataTable.Columns)
                {
                    if (dcl.ColumnName != "dcdr_team" && dcl.ColumnName != "dcom_NO" && dcl.ColumnName != "dcdr_userName" && dcl.ColumnName != "MTotal" && dcl.ColumnName != "MHours" && dcl.ColumnName != "dcdr_userid"
                      && !dcl.ColumnName.Contains("M") && !dcl.ColumnName.Contains("H") && !dcl.ColumnName.Contains("D") && !dcl.ColumnName.Contains("Q") && !dcl.ColumnName.Contains("R") && count > 0)
                    {

                        //合并表头
                        excel.ws.Cells[1, 3 + index] = dcl.ColumnName;
                        excel.UniteCells(excel.ws, 1, 3 + index, 1, 3 + index + 3);
                        excel.ws.Cells[2, 3 + index] = schedule[dcl.ColumnName];
                        excel.UniteCells(excel.ws, 2, 3 + index, 2, 3 + index + 3);

                        excel.ws.Cells[3, 3 + index] = "班次";
                        excel.ws.Cells[3, 3 + index + 1] = "出勤地点";
                        excel.ws.Cells[3, 3 + index + 2] = "调班";
                        excel.ws.Cells[3, 3 + index + 3] = "备注";
                        ((Excel.Range)excel.ws.Columns[3 + index , System.Type.Missing]).ColumnWidth = 6;
                        ((Excel.Range)excel.ws.Columns[3 + index + 1, System.Type.Missing]).ColumnWidth = 10;
                        ((Excel.Range)excel.ws.Columns[3 + index + 2, System.Type.Missing]).ColumnWidth = 8;
                        ((Excel.Range)excel.ws.Columns[3 + index + 3, System.Type.Missing]).ColumnWidth = 8;

                        index = index + 4;
                        count--;
                    }
                }


                //  设置背景色及合并
                string cell = sourceDataTable.Rows[0]["dcom_NO"].ToString();
                //合并

                for (int i = 0; i < sourceDataTable.Rows.Count; i++)
                {

                    ((Excel.Range)excel.ws.Rows[ i+1, System.Type.Missing]).RowHeight = 18;
                    //设置背景色
                    if (i % 2 == 0)
                    {
                        ((Excel.Range)excel.ws.Rows[4 + i, System.Type.Missing]).Interior.ColorIndex = 19;
                    }
                    else
                    {
                        ((Excel.Range)excel.ws.Rows[4 + i, System.Type.Missing]).Interior.ColorIndex = 39;
                    }

                }

                ((Excel.Range)excel.ws.Columns[1, System.Type.Missing]).Interior.ColorIndex = 0;
                ((Excel.Range)excel.ws.Rows[1, System.Type.Missing]).Interior.ColorIndex = 19;
                ((Excel.Range)excel.ws.Rows[2, System.Type.Missing]).Interior.ColorIndex = 19;
                ((Excel.Range)excel.ws.Rows[3, System.Type.Missing]).Interior.ColorIndex = 39;

                excel.InsertTable(callPB, excel.ws, 4, 1);

                excel.SaveAs(string.Format("{0}{1}", filePath, fileName));

                excel.Close();
                excel.KillExcelProcess();

                MessageBoxHelper.ShowTips(string.Format("导出 {0}  成功!", fileName));
            }
            catch (System.Exception ex)
            {
                //MessageBoxHelper.ShowError(string.Format("导出排班表失败: {0}", ex.Message.ToString()));
                MessageBoxHelper.ShowError(ex);
            }

            _viewModel.IsExporting = false;
            tip.Visibility = Visibility.Collapsed;
            tip.Close();

        }
        private DataTable GetCallTableSimplify(int days)
        {
            DataTable callTable = new DataTable();

            DataColumn dc1 = new DataColumn("Group", System.Type.GetType("System.String"));         // 级别
            //DataColumn dc2 = new DataColumn("Num", System.Type.GetType("System.String"));     //序号
            //DataColumn dc3 = new DataColumn("DriverGroup", System.Type.GetType("System.String"));  //司机组ID
            DataColumn dc4 = new DataColumn("Driver", System.Type.GetType("System.String")); //司机
            //DataColumn dc5 = new DataColumn("MTotal", System.Type.GetType("System.String")); //总公里数
            //DataColumn dc6 = new DataColumn("MHours", System.Type.GetType("System.String")); //总小时数
            callTable.Columns.Add(dc1);
            //callTable.Columns.Add(dc2);
            //callTable.Columns.Add(dc3);
            callTable.Columns.Add(dc4);
            //callTable.Columns.Add(dc5);
            //callTable.Columns.Add(dc6);
            for (int i = 0; i < days; i++)
            {
                DataColumn dc = new DataColumn("Date" + i.ToString(), System.Type.GetType("System.String"));  //日期
                callTable.Columns.Add(dc);
                DataColumn dq = new DataColumn("Date" + i.ToString() + "Q", System.Type.GetType("System.String")); //出勤信息
                callTable.Columns.Add(dq);
                //DataColumn dm = new DataColumn("Date" + i.ToString() + "M", System.Type.GetType("System.String")); //公里数
                //callTable.Columns.Add(dm);
                //DataColumn dh = new DataColumn("Date" + i.ToString() + "H", System.Type.GetType("System.String")); //小时数
                //callTable.Columns.Add(dh);
                DataColumn dd = new DataColumn("Date" + i.ToString() + "D", System.Type.GetType("System.String")); //换班
                callTable.Columns.Add(dd);
                DataColumn dr = new DataColumn("Date" + i.ToString() + "R", System.Type.GetType("System.String")); //备注
                callTable.Columns.Add(dr);

            }
            return callTable;
        }
        private DataTable GetCallTable(int days)
        {
            DataTable callTable = new DataTable();

            DataColumn dc1 = new DataColumn("Group", System.Type.GetType("System.String"));         // 级别
            DataColumn dc2 = new DataColumn("Num", System.Type.GetType("System.String"));     //序号
            DataColumn dc3 = new DataColumn("DriverGroup", System.Type.GetType("System.String"));  //司机组ID
            DataColumn dc4 = new DataColumn("Driver", System.Type.GetType("System.String")); //司机
            DataColumn dc5 = new DataColumn("MTotal", System.Type.GetType("System.String")); //总公里数
            DataColumn dc6 = new DataColumn("MHours", System.Type.GetType("System.String")); //总小时数
            callTable.Columns.Add(dc1);
            callTable.Columns.Add(dc2);
            callTable.Columns.Add(dc3);
            callTable.Columns.Add(dc4);
            callTable.Columns.Add(dc5);
            callTable.Columns.Add(dc6);
            for (int i = 0; i < days; i++)
            {
                DataColumn dc = new DataColumn("Date" + i.ToString(), System.Type.GetType("System.String"));  //日期
                callTable.Columns.Add(dc);
                DataColumn dq = new DataColumn("Date" + i.ToString() + "Q", System.Type.GetType("System.String")); //出勤信息
                callTable.Columns.Add(dq);
                DataColumn dm = new DataColumn("Date" + i.ToString() + "M", System.Type.GetType("System.String")); //公里数
                callTable.Columns.Add(dm);
                DataColumn dh = new DataColumn("Date" + i.ToString() + "H", System.Type.GetType("System.String")); //小时数
                callTable.Columns.Add(dh);
                DataColumn dd = new DataColumn("Date" + i.ToString() + "D", System.Type.GetType("System.String")); //换班
                callTable.Columns.Add(dd);
                DataColumn dr = new DataColumn("Date" + i.ToString() + "R", System.Type.GetType("System.String")); //备注
                callTable.Columns.Add(dr);

            }
            return callTable;
        }
        //初始化表中的数据
        private void InitCallTableSimplify(ref DataTable table, DataTable sourceDataTable, int countDays)
        {
            int index = 1;
            int countone = sourceDataTable.Select("dcdr_team=1").Count();
            int counttwo = sourceDataTable.Select("dcdr_team=2").Count();
            int countthree = sourceDataTable.Select("dcdr_team=3").Count();
            string cellContent = sourceDataTable.Rows[0]["dcom_NO"].ToString();

            int constColumnCount = 6;
            int lunhuiColumnCount = 6;
            for (int i = 0; i < sourceDataTable.Rows.Count; i++)
            {
                string tem = sourceDataTable.Rows[i]["dcom_NO"].ToString();
                DataRow row = table.NewRow();
                //row["Group"] = sourceDataTable.Rows[i][1].ToString();
                if (sourceDataTable.Rows[i][1].ToString() == "1")
                {
                    row["Group"] = "电客车一组";
                }
                else if (sourceDataTable.Rows[i][1].ToString() == "2")
                {
                    row["Group"] = "电客车二组";
                }
                else if (sourceDataTable.Rows[i][1].ToString() == "3")
                {
                    row["Group"] = "电客车三组";
                }
                else if (sourceDataTable.Rows[i][1].ToString() == "4")
                {
                    row["Group"] = "电客车四组";
                }
                else
                    row["Group"] = sourceDataTable.Rows[i][1].ToString();
                if (tem != cellContent)
                {
                    cellContent = tem;
                    index++;
                }
                if (i == countone)
                {
                    index = 1;
                }
                if (i == countone + counttwo)
                {
                    index = 1;
                }
                if (i == countone + counttwo + countthree)
                {
                    index = 1;
                }
                //row["Num"] = index.ToString();
                //row["DriverGroup"] = sourceDataTable.Rows[i][2].ToString();
                row["Driver"] = sourceDataTable.Rows[i][3].ToString();
                //row["MTotal"] = sourceDataTable.Rows[i][4].ToString();
                //row["MHours"] = sourceDataTable.Rows[i][5].ToString();

                for (int j = 0; j < (sourceDataTable.Columns.Count - constColumnCount) / lunhuiColumnCount; j++)
                {
                    row["Date" + j.ToString()] = sourceDataTable.Rows[i][constColumnCount + j * lunhuiColumnCount].ToString();
                    //row["Date" + j.ToString() + "M"] = sourceDataTable.Rows[i][constColumnCount + 1 + j * lunhuiColumnCount].ToString();
                    //row["Date" + j.ToString() + "H"] = sourceDataTable.Rows[i][constColumnCount + 2 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "Q"] = sourceDataTable.Rows[i][constColumnCount + 3 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "D"] = sourceDataTable.Rows[i][constColumnCount + 4 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "R"] = sourceDataTable.Rows[i][constColumnCount + 5 + j * lunhuiColumnCount].ToString();
                }

                table.Rows.Add(row);
            }
        }

        //初始化表中的数据
        private void InitCallTable(ref DataTable table, DataTable sourceDataTable, int countDays)
        {
            int index = 1;
            int countone = sourceDataTable.Select("dcdr_team=1").Count();
            int counttwo = sourceDataTable.Select("dcdr_team=2").Count();
            int countthree = sourceDataTable.Select("dcdr_team=3").Count();
            string cellContent = sourceDataTable.Rows[0]["dcom_NO"].ToString();

            int constColumnCount = 6;
            int lunhuiColumnCount = 6;
            for (int i = 0; i < sourceDataTable.Rows.Count; i++)
            {
                string tem = sourceDataTable.Rows[i]["dcom_NO"].ToString();
                DataRow row = table.NewRow();
                //row["Group"] = sourceDataTable.Rows[i][1].ToString();
                if (sourceDataTable.Rows[i][1].ToString() == "1")
                {
                    row["Group"] = "电客车一组";
                }
                else if (sourceDataTable.Rows[i][1].ToString() == "2")
                {
                    row["Group"] = "电客车二组";
                }
                else if (sourceDataTable.Rows[i][1].ToString() == "3")
                {
                    row["Group"] = "电客车三组";
                }
                else if (sourceDataTable.Rows[i][1].ToString() == "4")
                {
                    row["Group"] = "电客车四组";
                }else
                    row["Group"] = sourceDataTable.Rows[i][1].ToString();
                if (tem != cellContent)
                {
                    cellContent = tem;
                    index++;
                }
                if (i == countone)
                {
                    index = 1;
                }
                if (i == countone + counttwo)
                {
                    index = 1;
                }
                if (i == countone + counttwo + countthree)
                {
                    index = 1;
                }
                row["Num"] = index.ToString();
                row["DriverGroup"] = sourceDataTable.Rows[i][2].ToString();
                row["Driver"] = sourceDataTable.Rows[i][3].ToString();
                row["MTotal"] = sourceDataTable.Rows[i][4].ToString();
                row["MHours"] = sourceDataTable.Rows[i][5].ToString();

                for (int j = 0; j < (sourceDataTable.Columns.Count - constColumnCount) / lunhuiColumnCount; j++)
                {
                    row["Date" + j.ToString()] = sourceDataTable.Rows[i][constColumnCount + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "M"] = sourceDataTable.Rows[i][constColumnCount + 1 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "H"] = sourceDataTable.Rows[i][constColumnCount+2 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "Q"] = sourceDataTable.Rows[i][constColumnCount+3 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "D"] = sourceDataTable.Rows[i][constColumnCount+4 + j * lunhuiColumnCount].ToString();
                    row["Date" + j.ToString() + "R"] = sourceDataTable.Rows[i][constColumnCount + 5 + j * lunhuiColumnCount].ToString();
                }

                table.Rows.Add(row);
            }
        }

        //关闭窗口时释放导出Excel线程资源
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
           
            //if ( !_viewModel.IsExporting || isShowing)
            //{
            //    MessageBoxHelper.ShowTips("无法关闭窗口：请等候操作完成后重试！");
            //    e.Cancel = true;
            //}
            //try
            //{
            //    if (ExportAssignExcelThread != null)
            //        if (ExportAssignExcelThread.IsAlive)
            //            ExportAssignExcelThread.Abort();
            //}
            //catch (System.Exception ex)
            //{
            //}
            //finally
            //{
            //    ExportAssignExcelThread = null;
            //}
        }

        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            dpStartDate.SelectedDate = null;
            dpEndDate.SelectedDate = null;
            ComboBox cmbPlane =(ComboBox)sender ;
            string strPlane = cmbPlane.SelectedValue.ToString();
            string[] ArrayPlane = strPlane.Split('到');
            if (ArrayPlane.Length == 2)
            {
                planeStartDay=ArrayPlane[0];
                planeEndDay =ArrayPlane[1];
                dpStartDate.DisplayDateStart =Convert.ToDateTime(planeStartDay);
                dpStartDate.DisplayDateEnd = Convert.ToDateTime(planeEndDay);
                dpEndDate. DisplayDateStart = Convert.ToDateTime(planeStartDay);
                dpEndDate.DisplayDateEnd = Convert.ToDateTime(planeEndDay);
            }
            else
            {
                MessageBox.Show("数据出错，请联系管理员");
            }
        }

        private void textBoxR_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //MouseDoubleClick="textBoxR_MouseDoubleClick"
            TextBox tb = sender as TextBox;
            tb.IsReadOnly = false;
        }



        private void dataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            try
            {
                
                TextBox tb = e.EditingElement as TextBox;
                
                DataTable dt = (dataGrid.ItemsSource as DataView).Table;
                int actualColumnIndex=5+(e.Column.DisplayIndex-5)*3;
                string userid = dt.Rows[e.Row.GetIndex()]["dcdr_userid"].ToString();
                string columnName=dt.Columns[actualColumnIndex].ToString();
                string date = columnName.Remove(columnName.Length - 1);
                string key = userid + "|" + date;
                string old = dt.Rows[e.Row.GetIndex()][actualColumnIndex].ToString();
                if (old != tb.Text)
                {
                    if (updatedBeizhu.ContainsKey(key))
                    {
                        updatedBeizhu[key] = tb.Text;
                    }
                    else
                    {
                        updatedBeizhu.Add(key, tb.Text);
                    }
                }

                _driverTeamViewModel.UpdateDriverCombineCrossingRoadPlaneRemark(updatedBeizhu);
                updatedBeizhu.Clear();
                
            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex.Message);
            }
        }

        private void btn_saveUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (updatedBeizhu.Count > 0)
                {
                    var result = MessageBoxHelper.ConfirmYesNoCancel("是否确认保存修改？");
                    if (result == MessageBoxResult.Yes)
                    {
                        //string format = "update DriverCombineCrossingRoadPlane set dcdr_reamrkNew='?' where dcdr_userID=? and dcdr_date=CONVERT(datetime,'?');";
                        _driverTeamViewModel.UpdateDriverCombineCrossingRoadPlaneRemark(updatedBeizhu);

                    }
                }

            }
            catch (Exception ex)
            {
                MessageBoxHelper.ShowError(ex.Message);
            }
        }

        private void txtDriverNo_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox txt = sender as TextBox;

            //屏蔽非法按键
            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)
            {
                if (txt.Text.Contains(".") && e.Key == Key.Decimal)
                {
                    e.Handled = true;
                    return;
                }
                e.Handled = false;
            }
            else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
            {
                if (txt.Text.Contains(".") && e.Key == Key.OemPeriod)
                {
                    e.Handled = true;
                    return;
                }
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }


        }

        private void txtDriverNo_TextChanged(object sender, TextChangedEventArgs e)
        {
            //屏蔽中文输入和非法字符粘贴输入
            TextBox textBox = sender as TextBox;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                double num = 0;
                if (!Double.TryParse(textBox.Text, out num))
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);
                }
            }


        }
    }
}
